"use strict";
import axios from "axios";
import store from "@/store";
import router from "@/router";
import { Toast } from "vant";

axios.defaults.timeout = 10000;
// post请求头
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded;charset=UTF-8";
/* 请求拦截器 */
axios.interceptors.request.use(
  (config) => {
    // console.log(config);
    const token = store.state.user.token;
    config.headers.token = token;

    if (config.data != undefined) {
      if (config.headers.token == false && token) {
        Toast({
          message: "请登录",
          duration: 3000,
          forbidClick: true,
        });
        router.push("/login");
      }
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
/* 响应拦截器 */
axios.interceptors.response.use(
  (response) => {
    // console.log(response);
    return response;
  },
  (error) => {
    if (error.response.status) {
      switch (error.response.status) {
        case 401:
          router.replace({
            name: "Login",
          });
          break;
        // 403 token过期
        // 登录过期对用户进行提示
        // 清除本地token和清空vuex中token对象
        // 跳转登录页面
        case 403:
          Toast({
            message: "请求超时,请重新登录",
            duration: 3000,
            forbidClick: true,
          });
          window.sessionStorage.removeItem("token");
          store.commit("loginSuccess", null);
          setTimeout(() => {
            router.replace({
              name: "Login",
            });
          }, 2000);
          break;
        case 404:
          Toast({
            message: "无网络",
            duration: 3000,
            forbidClick: true,
          });
          break;
        case 500:
          Toast({
            message: "未知错误",
            duration: 3000,
            forbidClick: true,
          });
          break;
        default:
          Toast({
            message: error.response.data.message,
            duration: 1500,
            forbidClick: true,
          });
      }
    }
    return Promise.reject(error);
  }
);
export function get(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params: {
          params,
        },
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch((error) => {
        reject(error);
      });
  });
}
export function post(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, QS.stringify(params))
      .then((res) => {
        resolve(res.data);
      })
      .catch((error) => {
        reject(error);
      });
  });
}
